package mrpanyu.guitool.dbcodegen.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.Types;

/**
 * 相关代码中用到的一些工具类方法整合到一起
 */
public final class DbCodeGeneratorUtils {

	public static boolean isBlank(CharSequence text) {
		return text == null || text.toString().trim().length() == 0;
	}

	public static boolean isNotBlank(CharSequence text) {
		return !isBlank(text);
	}

	public static String trimToEmpty(String text) {
		if (text == null) {
			return "";
		} else {
			return text.trim();
		}
	}

	public static String getJdbcTypeName(int jdbcType) {
		try {
			Field[] fields = Types.class.getFields();
			for (Field field : fields) {
				if (Modifier.isStatic(field.getModifiers()) && ((Number) field.get(null)).intValue() == jdbcType) {
					return field.getName();
				}
			}
			return null;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String loadResource(String path, String encoding) throws IOException {
		InputStream ins = null;
		if (path.startsWith("classpath:")) {
			String realPath = path.substring("classpath:".length());
			while (realPath.startsWith("/")) {
				realPath = realPath.substring(1);
			}
			ins = DbCodeGeneratorUtils.class.getClassLoader().getResourceAsStream(realPath);
		} else {
			String realPath = path;
			if (realPath.startsWith("file://")) {
				realPath = realPath.substring("file://".length());
			} else if (realPath.startsWith("file:")) {
				realPath = realPath.substring("file:".length());
			}
			ins = new FileInputStream(realPath);
		}
		String content = new String(readFully(ins), encoding);
		ins.close();
		return content;
	}

	public static byte[] readFully(InputStream in) {
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] buf = new byte[1024];
			int len = in.read(buf);
			while (len > 0) {
				baos.write(buf, 0, len);
				len = in.read(buf);
			}
			return baos.toByteArray();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public static void setProperty(Object bean, String propertyName, Object value) {
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
			PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
			PropertyDescriptor propertyDescriptor = null;
			for (PropertyDescriptor pd : pds) {
				if (propertyName.equals(pd.getName())) {
					propertyDescriptor = pd;
					break;
				}
			}
			propertyDescriptor.getWriteMethod().invoke(bean, value);
		} catch (Exception e) {
			throw new RuntimeException("Error setting property '" + propertyName + "' on bean '" + bean.getClass().getName() + "'", e);
		}
	}

	private DbCodeGeneratorUtils() {
	}

}
